const express = require("express")
const router = express.Router()
const Household = require("../models/household")

// 获取所有住户信息
router.get("/", async (req, res) => {
  try {
    const households = await Household.findAll({
      where: { delete_at: null },
    })
    res.json({ code: 200, data: households, message: "获取住户列表成功" })
  } catch (error) {
    res.json({ code: 500, message: "获取住户列表失败" })
  }
})

// 获取单元下的所有住户
router.get("/getHouseholdsByUnit/:unitId", async (req, res) => {
  try {
    const households = await Household.findAll({
      where: { unit_id: req.params.unitId },
      order: [
        ["floor_num", "ASC"],
        ["house_address", "ASC"],
      ],
    })
    res.json({ code: 200, data: households, message: "获取住户列表成功" })
  } catch (error) {
    res.json({ code: 500, message: "获取住户列表失败" })
  }
})

// 获取单个住户信息
router.get("/getHousehold/:id", async (req, res) => {
  try {
    const household = await Household.findByPk(req.params.id)
    if (!household) return res.json({ code: 404, message: "住户不存在" })
    res.json({ code: 200, data: household, message: "获取住户信息成功" })
  } catch (error) {
    res.json({ code: 500, message: "获取住户信息失败" })
  }
})

// 添加住户信息
router.post("/addHousehold", async (req, res) => {
  try {
    const household = await Household.create({
      ...req.body,
      water_fee: req.body.water_fee || 0,
      electric_fee: req.body.electric_fee || 0,
      property_fee: req.body.property_fee || 0,
      is_paid: req.body.is_paid || false,
    })
    res.json({ code: 200, data: household, message: "添加住户成功" })
  } catch (error) {
    res.json({ code: 500, message: "添加住户失败" })
  }
})

// 更新住户信息
router.put("/updateHousehold/:id", async (req, res) => {
  try {
    const household = await Household.findByPk(req.params.id)
    if (!household) return res.json({ code: 404, message: "住户不存在" })
    await household.update(req.body)
    res.json({ code: 200, message: "更新住户信息成功" })
  } catch (error) {
    res.json({ code: 500, message: "更新住户信息失败" })
  }
})

// 删除住户信息
router.delete("/deleteHousehold/:id", async (req, res) => {
  try {
    const household = await Household.findByPk(req.params.id)
    if (!household) return res.json({ code: 404, message: "住户不存在" })
    await household.update({ delete_at: new Date() })
    res.json({ code: 200, message: "删除成功" })
  } catch (error) {
    res.json({ code: 500, message: "删除失败" })
  }
})

// 获取楼栋下的所有住户费用信息
router.get("/getHouseholdsByBuilding/:buildingId", async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query
    const offset = (page - 1) * pageSize
    const limit = parseInt(pageSize)

    const households = await Household.findAndCountAll({
      where: {
        building_name: req.params.buildingId,
        delete_at: null,
      },
      attributes: [
        "id",
        "building_name",
        "unit_number",
        "house_address",
        "owner_name",
        "water_fee",
        "electric_fee",
        "property_fee",
        "is_paid",
        "create_at",
        "update_at",
      ],
      offset,
      limit,
      order: [["create_at", "DESC"]],
    })

    res.json({
      code: 200,
      data: {
        list: households.rows.map((item) => ({
          ...item.toJSON(),
          key: item.id,
        })),
        total: households.count,
        page: parseInt(page),
        pageSize: limit,
      },
      message: "获取住户费用列表成功",
    })
  } catch (error) {
    res.json({ code: 500, message: "获取住户费用列表失败" })
  }
})

module.exports = router
